<?php
/**
 * User: hjd-yao
 * Date: 2018/11/15
 * Time: 17:20
 */

namespace App\Http\Controllers\Backend;


use App\Helpers\SelfEncrypt;
use App\Helpers\SelfResponse;
use App\Http\Controllers\BackendController;
use App\Http\Requests\AdminPwdRequest;
use App\Http\Requests\AdminRequest;
use App\Models\ManageAdminModel;
use App\Models\System\RoleModel;
use Illuminate\Http\Request;


class AdminController extends BackendController
{
    private static $_adminModel;
    public function __construct()
    {
        self::$_adminModel = ManageAdminModel::init();
    }

    /**
     * @title 管理员列表
     * @return View
     */
    public function index()
    {
        $login_id=self::$_adminModel->getLoginId();
        $list=self::$_adminModel->whereRaw("FIND_IN_SET(?,`parent_ids`)",[$login_id])
               ->orWhere('mgr_id',$login_id)->paginate($this->getPerPageNum());
        $roles = RoleModel::where('status',1)->pluck('title','id')->toArray();
        return view('backend::admin.index',[
            'list'=>$list,
            'roles'=>$roles,
            'page_title'=>'管理员列表',
        ]);
    }

    /**
     * @title 管理员信息
     * @param $admin_name
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function info($admin_name)
    {
        $info = ManageAdminModel::where('mgr_name',SelfEncrypt::encrypt($admin_name))
            ->select(['mgr_name','mgr_email','login_count','login_at','login_ip','created_at'])->first();
        return view('backend::admin.info',[
            'page_title'=>$info->mgr_name.'信息',
            'info'=>$info
        ]);
    }

    /**
     * @title 添加管理员
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showAddAdminForm()
    {
        $roles = RoleModel::where('status',1)->pluck('title','id')->toArray();
        return view('backend::admin.add',[
            'page_title'=>'添加管理员',
            'roles'=>$roles
        ]);
    }

    /**
     * @title 保存新增管理员
     * @param AdminRequest $request
     * @return SelfResponse|\Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function save(AdminRequest $request)
    {
        $data = $request->post();
        if(self::$_adminModel->addAdmin($data)){
            return SelfResponse::success('新增管理员成功','b_Admin_index');
        }
        return SelfResponse::error('新增管理员失败!');
    }

    /**
     * @title 编辑管理员
     * @param $admin_name
     * @return SelfResponse|\Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function showEditAdminForm($admin_name)
    {
        $info = self::$_adminModel->where('mgr_name',SelfEncrypt::encrypt($admin_name))->where(function ($query){
                        $login_id=self::$_adminModel->getLoginId();
                        $query->whereRaw("FIND_IN_SET(".$login_id.",`parent_ids`)")
                                ->orWhere('mgr_id',$login_id);
                })->first();

        if(!$info){
            return SelfResponse::error('修改信息不存在或无权修改');
        }

        return view('backend::admin.edit',[
            'page_title'=>'编辑'.$info->mgr_name.'信息',
            'info'=>$info
        ]);
    }

    /**
     * @title 更新管理员信息
     * @param AdminRequest $request
     * @param $admin_name
     * @return SelfResponse|\Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function update(AdminRequest $request,$admin_name)
    {
        $info = self::$_adminModel->where('mgr_name',SelfEncrypt::encrypt($admin_name))->where(function ($query){
            $login_id=self::$_adminModel->getLoginId();
            $query->whereRaw("FIND_IN_SET(".$login_id.",`parent_ids`)")
                ->orWhere('mgr_id',$login_id);
        })->first();

        if(!$info){
            return SelfResponse::error('修改信息不存在或无权修改');
        }
        $data = $request->only(['admin_name','admin_mobile','admin_email']);
        if(self::$_adminModel->editAdmin($data,$admin_name)){
            return SelfResponse::success('修改成功','b_Admin_index');
        }
        return SelfResponse::error('修改失败!');
    }

    /**
     * @title 删除管理员
     * @param $admin_name
     * @return SelfResponse|\Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function delete($admin_name)
    {
        $info = self::$_adminModel->where('mgr_name',SelfEncrypt::encrypt($admin_name))->where(function ($query){
            $login_id=self::$_adminModel->getLoginId();
            $query->whereRaw("FIND_IN_SET(".$login_id.",`parent_ids`)")
                ->where('mgr_id','<>',$login_id);
        })->first();

        if(!$info){
            return SelfResponse::error('修改信息不存在或无权修改');
        }

        if(self::$_adminModel->deleteAdmin($info->mgr_id)){
            return SelfResponse::success('删除成功','b_Admin_index');
        }
        return SelfResponse::error(self::$_adminModel->getErrorMsg()?:'删除失败');
    }

    /**
     * @title 启用/禁用管理员
     * @param $admin_name
     * @return SelfResponse|\Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function switchAdminStatus($admin_name)
    {
        $info = self::$_adminModel->where('mgr_name',SelfEncrypt::encrypt($admin_name))->where(function ($query){
            $login_id=self::$_adminModel->getLoginId();
            $query->whereRaw("FIND_IN_SET(".$login_id.",`parent_ids`)")
                ->where('mgr_id','<>',$login_id);
        })->first();

        if(!$info){
            return SelfResponse::error('修改信息不存在或无权修改');
        }
        $status = abs($info->is_enable - 1);
        $status = $status>1?1:$status;
        if(self::$_adminModel->changeStatus($admin_name,$status)){
            return SelfResponse::success('成功','b_Admin_index');
        }
        return SelfResponse::error(self::$_adminModel->getErrorMsg()?:'删除失败');
    }

    /**
     * @title 修改密码
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function changePwdForm()
    {
        return view('backend::admin.change_pwd');
    }

    /**
     * @title 保存修改密码
     * @param AdminPwdRequest $request
     * @param $action
     * @return SelfResponse|\Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function updatePwd(AdminPwdRequest $request,$action)
    {
        $data = $request->post();
        $login_id = self::$_adminModel->getLoginId();
        if($action == 'login'){
            if(!self::$_adminModel->checkLoginPwd($data['old_login_pwd'],$login_id)){
                return SelfResponse::error(self::$_adminModel->getErrorMsg()?:'原登录密码错误');
            }
            if(!self::$_adminModel->updateLoginPwd($data['login_pwd'],$login_id)){
                return SelfResponse::error(self::$_adminModel->getErrorMsg()?:'密码修改失败');
            }
            return SelfResponse::success('密码修改成功','b_Admin_index');

        }else{
            if(!self::$_adminModel->checkSafePwd($data['old_safe_pwd'],$login_id)){
                return SelfResponse::error(self::$_adminModel->getErrorMsg()?:'原安全密码错误');
            }
            if(!self::$_adminModel->updateSafePwd($data['safe_pwd'],$login_id)){
                return SelfResponse::error(self::$_adminModel->getErrorMsg()?:'密码修改失败');
            }
            return SelfResponse::success('密码修改成功','b_Admin_index');
        }
    }

    /**
     * @title 重置密码
     * @param $admin_name
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function resetPwdForm($admin_name)
    {
        return view('backend::admin.reset_pwd',[
            'page_title'=>'重置密码',
            'admin_name'=>$admin_name
        ]);
    }

    /**
     * @title 执行重置密码
     * @param AdminPwdRequest $request
     * @param $admin_name
     * @param $action
     * @return SelfResponse|\Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function reset(AdminPwdRequest $request,$admin_name,$action)
    {
        $login_id=self::$_adminModel->getLoginId();
        $info = self::$_adminModel->where('mgr_name',SelfEncrypt::encrypt($admin_name))->where(function ($query) use($login_id){
            $query->whereRaw("FIND_IN_SET(".$login_id.",`parent_ids`)")
                ->where('mgr_id','<>',$login_id);
        })->first();

        if(!$info){
            return SelfResponse::error('修改信息不存在或无权修改');
        }

        $data = $request->post();
        if(!self::$_adminModel->checkSafePwd($data['my_safe_pwd'],$login_id)){
            return SelfResponse::error('安全密码错误!');
        }

        if($action == 'login'){
            if(!self::$_adminModel->updateLoginPwd($data['login_pwd'],$info->mgr_id)){
                return SelfResponse::error(self::$_adminModel->getErrorMsg()?:'密码重置失败');
            }
            return SelfResponse::success('登录密码重置成功','b_Admin_index');

        }else{
            if(!self::$_adminModel->updateSafePwd($data['safe_pwd'],$info->mgr_id)){
                return SelfResponse::error(self::$_adminModel->getErrorMsg()?:'密码修改失败');
            }
            return SelfResponse::success('安全密码重置成功','b_Admin_index');
        }
    }

    /**
     * @title 分配角色
     * @param Request $request
     * @param $admin_name
     * @return SelfResponse|\Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function grantRoles(Request $request,$admin_name)
    {
        $roles = RoleModel::where('status',1)->pluck('title','id')->toArray();
        $info = self::$_adminModel->where('mgr_name',SelfEncrypt::encrypt($admin_name))->first();
        if($request->isMethod('post')){
            $post_roles = $request->post('my_roles');
            if(!$info){
                return SelfResponse::error('分配角色的管理不存在！');
            }
            $new_roles = array_intersect(array_keys($roles),$post_roles);
            if(self::$_adminModel->where('mgr_name',SelfEncrypt::encrypt($admin_name))->update(['my_roles'=>arr2str($new_roles)])){
                return SelfResponse::success('分配角色成功！','b_Admin_index');
            }
            return SelfResponse::error('分配角色失败,请重新尝试！');
        }else{
            return view('backend::admin.grant_roles',[
                'page_title'=>'给'.$admin_name.'分配角色',
                'roles'=>$roles,
                'admin_name'=>$info->mgr_name,
                'my_roles'=>$info->my_roles
            ]);
        }
    }
}